<template>
  <!--分析报表-案场客流查询 -->
  <el-row style="height:100%">
    <page report="true">
      <div class="page-content report-con">
        <reportheader
          :option="option"
          :isArea="true"
          :global="global"
        ></reportheader>
        <div class="hei13"></div>
        <div 
          class='loadingClass'
          v-loading="xxloading"
          element-loading-text="请点击查询报表获取相关数据"
          element-loading-spinner="el-icon-caret-top"
          element-loading-background="rgba(245, 248, 254, 1)">
        <KPItimeEcharts :title="global.title" :y_danwei="y_danwei"
                          :x_data="xData"  :y_name="yName"
                          :y_data="yData" ref='echarts' 
        ></KPItimeEcharts>
        <div class="hei13"></div>
        <KPItimeTable  :tableData="table.tableData" :tableHead="table.tableHead"
                     ref='table' :title="global.title" :isShowExport="daochu" ></KPItimeTable>
        </div>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .loadingClass{
    .el-loading-mask{
      .el-loading-spinner{
        top: 80px;
        i{
          display: none;
        }
        .el-loading-text{
          font-size: 18px;
          font-weight: bold;
          color:#b4b6bd;
        }
      }
      
    }
  }
  .page-content {
    &.report-con {
      padding: 0 0;
    }

    padding: 15px;

    .fr {
      float: right;
    }

    .el-table {
      margin-bottom: 10px;
    }

    .paging {
      margin: 15px;
      height: 28px;
    }

    .hei13 {
      height: 15px;
      width: 100%;
    }
  }
</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import reportheader from "@/components/analyzeReport/reportpublic/reportKPItimeHead";
  import KPItimeEcharts from "@/components/analyzeReport/reportpublic/KPItimeEcharts";
  import KPItimeTable from "@/components/analyzeReport/reportpublic/KPItimeTable";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  let unit = reportGlobal.unit;
  let kpiName = reportGlobal.name;
  export default {
    data: function () {
      //表格数据
      var table = {
        tableData: [],
        tableHead: []
      }
      return {
        option: {
          shortcuts: 'dayShortcuts',
          caseTitle: "",
        },
        table: table,
        showType: 'time',  //展示类型(time:分时,distr:分布)
        DataV: {
          case_id:[],//案场id
          time:['',''], //日期
          duibi_time:['',''],//对比日期
          start_hm:[],   //开始时段
          end_hm:[],    //结束时段
        },      //head条件接收
        xData: [],
        yData: [],
        yName: [],
        y_danwei:'',
        titleText: "",
        commonData: null,
        timeSize: {
          list: [],
          check: ''
        },
        echartKpis: [],//echart指标
        global: {},//公共参数
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
        daochu:false,
        xxloading:true,   //提示信息遮罩层
      };
    },
    components: {
      page,
      reportheader,
      KPItimeEcharts,
      KPItimeTable,
    },
    inject: ["reload"],
    created() {
      for (let i in reportGlobal.queryList) {
        if (this.code == reportGlobal.queryList[i].code) {
          this.global = reportGlobal.queryList[i]
        }
      }
      this.option.caseTitle = this.global.caseTitle
    },
    mounted() {
      //条件改变
     this.$Bus.$on("UpCondition", (data)=>{
        if(this.xxloading)
        {
          this.xxloading=false;
        }
       this.DataV=data;
       this.daochu=data.daochu;
       this.Updata();
     });
    
     //切换企业时清空数据
     this.$Bus.$on('Remove', () => {
        this.removedata();
     });
    },
    beforeDestroy() {
      this.$Bus.$off('UpCondition')
      this.$Bus.$off('Remove')
    },
    watch: {
      //当route变化的时候，主要是报表之前传参
      $route(val){
        this.reload()
      },
    },
    methods: {
      Updata() {
        let url = "/sys/report_new/time_division_sum?group_type=area&"
        +"tags=" + this.global.tags + "&indicator_keys=" + this.DataV.kpiType + 
       "&interval=" + this.DataV.timeSizeCkeck;
        let url1= url+"&start_day=" + this.DataV.time[0] + "&end_day=" + this.DataV.time[1] + "&start_hm=" + this.DataV.start_hm + "&end_hm=" + this.DataV.end_hm;
        let url2=url+"&start_day=" + this.DataV.duibi_time[0] + "&end_day=" + this.DataV.duibi_time[1] + "&start_hm=" + this.DataV.start_hm + "&end_hm=" + this.DataV.end_hm;
        let params = {
          org_id_list : Array.of(this.DataV.area_id),
          org_type:3
        };
        let p1=new Promise((resolve,reject)=>{
          this.$api.post(url1,params)
          .then(data=>{
            if(data == '10001'){
                 this.$message.error('无权操作该数据')
                return
            }
            if(data.data){
              resolve(data.data);
            }
          })
          .catch(err=>{
             console.log(err);
          })
        });
        let p2=new Promise((resolve,reject)=>{
          this.$api.post(url2,params)
          .then(data=>{
            if(data == '10001'){
                this.$message.error('无权操作该数据')
                return
            }
            if(data.data){
                resolve(data.data);
            }
          })
          .catch(err=>{
             console.log(err);
          })
        })
        let p=Promise.all([p1,p2]);
        p.then(data=>{
          if((data[0].item_list&&data[0].item_list.length)||(data[1].item_list&&data[1].item_list.length)){
            this.Upecharts(data[0].item_list,data[1].item_list);
            this.Uptable(data[0].item_list,data[1].item_list);
          }
          else{
            this.$message({
              showClose: true,
              message: '没有数据！',
              type: 'warning'
            });
            this.removedata();
            this.$Bus.$emit("Loading", false);
          }
        })
        .catch(err=>{
           console.log(err);
          this.removedata();
          this.$Bus.$emit("Loading", false);
        })

      },

      getYname(Timearr){
        if(Timearr[0]==Timearr[1]){
          return Timearr[0];
        }
        else{
          return Timearr[0]+' ~ '+Timearr[1];
        }
      },
      

            //table提取指标对应的数据 //
      extractKpis(data, showKpislist) {
        let kpisval = [];
        for (let item in showKpislist) {
          let model = [];
          for (let i = 0; i < data.length; i++) {
            model.push(data[i][showKpislist[item]]);
          }
          kpisval.push(model);
        }
        return kpisval
      },
      //分时柱状图数据改变
      Upecharts(data,pkData) {
        let x_data=[];
        let y1=[];
        let y2=[];
        data = data==null?[]:data;
        pkData = pkData==null?[]:pkData;
        let n=data.length>=pkData.length?data.length:pkData.length;
        for(let i=0;i<n;i++)
        {
          x_data.push((i<data.length?data[i].time_tag:'-')+'\nvs.       \n'+ (i<pkData.length?pkData[i].time_tag:'-       ') );
          y1.push((i<data.length?data[i][this.DataV.kpiType]:'-'));
          y2.push((i<pkData.length?pkData[i][this.DataV.kpiType]:'-'));
        }
        let y_data=[];
        y_data.push(y1);
        y_data.push(y2);
        let y_name=[];
        y_name.push(this.getYname(this.DataV.time));
        y_name.push(this.getYname(this.DataV.duibi_time));
        this.y_danwei=kpiName[this.DataV.kpiType]+'/'+unit[this.DataV.kpiType];
        this.xData = x_data;
        this.yName = y_name;
        this.yData = y_data;
        this.$nextTick(() => {
          this.$refs.echarts.UpData(true);
          this.$Bus.$emit("Loading", false);
        })
        this.$Bus.$emit("Loading", false);
      },

      myIsNaN(value) { 
         return value !== value; 
      },
      Uptable(data,pkData) {
        let timeval = []; 
        let t_data = []; //组装表格数据
        let bianhuaV=[]; //变化值
        let bianhual=[];//变化率
        data = data==null?[]:data;
        pkData = pkData==null?[]:pkData;
        let n=data.length>=pkData.length?data.length:pkData.length;
        for(let i=0;i<n;i++)
        {
          timeval.push((i<data.length?data[i].time_tag:'-')+' vs. '+ (i<pkData.length?pkData[i].time_tag:'-') );
          let model={
            case_info_name:'变化值',
            area_name:'变化值',
          };
          let model2={
            case_info_name:'变化率',
            area_name:'变化率',
          }
          model[this.DataV.kpiType]=(i<data.length && i<pkData.length)?Number((data[i][this.DataV.kpiType]-pkData[i][this.DataV.kpiType]).toFixed(2)):'--';
          if(i<data.length && i<pkData.length)
          {
            let bcs=(parseFloat(data[i][this.DataV.kpiType])-parseFloat(pkData[i][this.DataV.kpiType]));
            let cs=parseFloat(pkData[i][this.DataV.kpiType]);
            if(cs!=0)
            {
              model2[this.DataV.kpiType]=((bcs/cs)*100).toFixed(2)+(unit[this.DataV.kpiType]=='%'?'':'%');
            }
            else{
              model2[this.DataV.kpiType]='--';
            }
          }
          else{
            model2[this.DataV.kpiType]='--';
          }
         
          if(this.myIsNaN(model2[this.DataV.kpiType])||model2[this.DataV.kpiType]=='NaN'||model2[this.DataV.kpiType]=='NaN%')
          {
            model2[this.DataV.kpiType]='0';
          }
          // model2[this.DataV.kpiType]=model2[this.DataV.kpiType]=='NaN'||(this.myIsNaN(model2[this.DataV.kpiType])&&(model2[this.DataV.kpiType]!='0.00%'))?'--':model2[this.DataV.kpiType];
          bianhuaV.push(model);
          bianhual.push(model2);
        }
        let t_head=[];
        for (let i = 0; i < timeval.length; i++) {
          let model = {};
            model.prop = model.label = timeval[i];
            t_head.push(model);
        }
        
         
        let showKpislist=Array.of(this.DataV.kpiType);
        let tempdata;
        let kpisval;
        kpisval = this.extractKpis(data, showKpislist);
        tempdata = this.getTableData(data, showKpislist, kpisval, timeval);
        t_data = [...t_data, ...tempdata];

        kpisval = this.extractKpis(pkData, showKpislist);
        tempdata = this.getTableData(pkData, showKpislist, kpisval, timeval,'对比时间');
        t_data = [...t_data, ...tempdata];
        
        kpisval = this.extractKpis(bianhuaV, showKpislist);
        tempdata = this.getTableData(bianhuaV, showKpislist, kpisval, timeval);
        t_data = [...t_data, ...tempdata];

        kpisval = this.extractKpis(bianhual, showKpislist);
        tempdata = this.getTableData(bianhual, showKpislist, kpisval, timeval,'',true);
        t_data = [...t_data, ...tempdata];
        
        


        this.table.tableData = [];
        this.table.tableHead = [];
        this.table.tableData = t_data;
        this.table.tableHead = t_head;
      },
  

      //table提取指标对应的数据 //
      extractKpis(data, showKpislist) {
        let kpisval = [];
        for (let item in showKpislist) {
          let model = [];
          for (let i = 0; i < data.length; i++) {
            model.push(data[i][showKpislist[item]]);
          }
          kpisval.push(model);
        }

        return kpisval;
      },

      //table 分开提取表格数据 （如平均、合计、案场等）;
      getTableData(data, showKpislist, kpisval, timeval,tiaojian='时间',islv=false) {
        let t_data = [];
        if(data.length){
          for (let i = 0; i < showKpislist.length && data.length > 0; i++) {
            let model = {};
            model.case_id=data[0].case_info_id;
            model.area_id=data[0].area_id;
            model.case = data[0].case_info_name == 'avg' ? '平均值' : (data[0].case_info_name == 'sum' ? '合计' : data[0].case_info_name);
            model.area = data[0].area_name;
            model.timeSlot=data[0].case_info_name=='变化值'?'变化值':(data[0].case_info_name=='变化率'?'变化率':tiaojian);
            model.kpi = this.getkpiName(showKpislist[i])+'('+unit[showKpislist[i]]+')';
            model.aver =unit[showKpislist[i]] == '%' ? this.getSumAver(kpisval[i], true,islv)+unit[showKpislist[i]]:this.getSumAver(kpisval[i], true,islv);
            model.sum = unit[showKpislist[i]] == '%' ? '--' : this.getSumAver(kpisval[i],false,islv);
            model.case_code = data[0].case_info_name == '变化值'?'变化值':(data[0].case_info_name=='变化率'?'变化率':data[0].case_code);
            for (let j = 0,s=0; j < timeval.length; j++) {
              let key = timeval[j];
              if(j<data.length)
              {
                model[key] =kpisval[i][s]==null?'':(unit[showKpislist[i]]=='%'?kpisval[i][s]+'%':kpisval[i][s]);
                s++;
              }
              else{
                model[key] ='-';
              }
            }
           var arr=kpisval[i].filter(item=>item);    //去掉数组中的null,undefined
           if(arr.length){
              model.max = arr.reduce(function(a , b){
                          return b > a ? b : a;
                        });
              model.min = arr.reduce(function(a , b){
                          return b < a ? b : a;
                        });
            }
            else{
              model.max =null
              model.min =null
            }
            t_data.push(model);
          }
        }
        return t_data;
      },

      //得到指标中文名
      getkpiName(kpiname) {
        return kpiName[kpiname];
      },
      //求和或平均值    求平均值isaver=true
      getSumAver(arr, isaver,islv=false) {
        if(islv)
        {
          return '--';
        }
        let sum = 0;
        for (let i = 0; i < arr.length; i++) {
          sum +=arr[i][arr[i].length-1]=='%'?parseFloat(arr[i]):(arr[i]=='--')?0:parseFloat(arr[i]);
        }
        if (isaver) {
          if(arr[0][arr[0].length-1]=='%'||unit[this.DataV.kpiType]=='%'||islv)
          {
              return '--';
          }
          else{
            
            return this.myIsNaN(((sum / arr.length).toFixed(2) * 100) / 100)?'--':((sum / arr.length).toFixed(2) * 100) / 100;
          }
        } else {
          if(islv)
          {
            return '--';
          }
          if(arr[0][arr[0].length-1]=='%')
          {
              return (sum.toFixed(2) * 100 / 100)+'%';
          }
          else{
            return sum.toFixed(2) * 100 / 100;
          }
        }
      },
      //清除数据
      removedata() {
        this.$refs.echarts.UpData(false);
        this.daochu=false;
        this.table.tableData = [];
        this.table.tableHead = [];
        this.commonData = null;
        this.DataV = {};
      },

      //echarts 周数显示
      getWeekShow() {
        let strtime = this.DataV.start_day;
        let endtime = this.DataV.end_day;
        let tempdate = moment(strtime).format("YYYY-MM-DD");
        let a_week = moment(tempdate).get('week');
        let end_tempdate = moment(endtime).format("YYYY-MM-DD");
        let end_a_week = moment(end_tempdate).get('week');
        let str = '';
        if (tempdate == end_tempdate) {
          str = end_tempdate + ' 周' + moment(endtime).format("d");
          return str;
        }
        if (a_week == end_a_week) {

          str = tempdate + ' ~ ' + end_tempdate + ' 第' + end_a_week + '周';

        } else {
          str = tempdate + ' 第' + a_week + '周 ~ ' + end_tempdate + ' 第' + end_a_week + '周';
        }
        return str;

      },

      //数组分项
      partArr(arr) {
       let rearr = [];
       let mode = [];
        for (let j = 0; j < arr.length; j++) {
          if (arr[j].case_info_id == this.DataV.case) {
            mode.push(arr[j]);
          }
        }
        rearr.push(mode);
        return rearr;
      },
      //判断是否开启导出按钮
      isShowExport(){
        if(this.showType == 'time'){
          for(let i in this.timeSize.list){
            if(this.timeSize.check == this.timeSize.list[i].tag){
              this.timeSize.isShow = this.timeSize.list[i].type == 'MIN' ? false : true
            }
          }
        }else{
          this.timeSize.isShow = true
        }

      }
    }
  };
</script>
